# myapp.rb
require 'sinatra'
require 'haml'
require 'tilt'
require 'sinatra/base'
# get '/' do
#   'Hello world!'
# end
get '/hello/:name' do
  # 匹配 "GET /hello/foo" 和 "GET /hello/bar"
  # params[:name] 的值是 'foo' 或者 'bar'
  "Hello #{params[:name]}!"
end
get '/hello2/:name' do |n|
  # 匹配"GET /hello/foo" 和 "GET /hello/bar"
  # params[:name] 的值是 'foo' 或者 'bar'
  # n 中存储了 params['name']
  "Hello #{n}!"
end

# get '/say/*/to/*' do
#   # 匹配 /say/hello/to/world
#   params[:splat] # => ["hello", "world"]
# end

# get '/download/*.*' do
#   # 匹配 /download/path/to/file.xml
#   params[:splat] # => ["path/to/file", "xml"]
# end

# get %r{/hello/([\w]+)} do
#   "Hello, #{params[:captures].first}!"
# end

get '/index' do
  haml :index
  # markdown :hello
end
get '/submit' do
  tilt :ht
  # markdown :hello
end
get '/:id' do
  @foo = Foo.find(params[:id])
  haml '%h1= @foo.name'
end

# def each
#     100.times { |i| yield "#{i}\n" }
# end
class Stream
  def each
    100.times { |i| yield "#{i}\n" }
  end
  # def sayHello
  #   yield hello
  # end
end
class Input
  def sayHello
    yeild hello
  end
end
class AllButPattern
  def initialize(except)
    @except = except
  end

  def to_pattern(options)
    return self
  end

  def params(route)
    return {} unless @except === route
  end
end

def all_but(pattern)
  AllButPattern.new(pattern)
end

get '/', :host_name => /\./ do
  "Admin Area, Access denied! "
  # redirect to('/hello/!^^!')
  status, headers, body = call env.merge("PATH_INFO" => '/hello/!^^!')
  [status, headers, body.map(&:upcase)]
  # "hello world" + 
  # sayHello
  # Stream.new
  # all_but("he")
  # Input.new
end

get '/', :provides => 'html' do
  haml :index
end

get '/', :provides => ['rss', 'atom', 'xml'] do
  builder :feed
end

post '/upload' do
  begin
    file = params[:file] # 获取上传的文件对象
    filename = file[:filename] # 获取文件名
    puts file
    # 保存文件到指定位置
    save_path = File.join('./public/access', filename)
  
    File.open(save_path, 'wb') do |f|
      f.write(file[:tempfile].read)
    end

    "File uploaded successfully!"
  rescue StandardError => e
    "An error occurred while uploading the file: #{e.message}"
  end
end

# get '/filename' do
#   send_file '../../public/img/R-C.jpg'
# end
set :bin, '172.28.160.1'
set :port, 2222